package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"time"

	"github.com/gin-gonic/gin"
)

type TaskLogService struct {
	repo repository.TaskLogRepository
}

func NewTaskLogService(repo repository.TaskLogRepository) *TaskLogService {
	return &TaskLogService{repo: repo}
}

func (s *TaskLogService) CreateLog(c *gin.Context) {
	var log model.TaskLog
	if err := c.ShouldBindJSON(&log); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.CreateLog(&log); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, log)
}

func (s *TaskLogService) GetLog(c *gin.Context) {
	id := c.Param("id")
	log, err := s.repo.GetLog(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, log)
}

func (s *TaskLogService) ListLogs(c *gin.Context) {
	taskID := c.Query("taskId")
	startTimeStr := c.Query("startTime")
	endTimeStr := c.Query("endTime")

	var startTime, endTime time.Time
	var err error

	if startTimeStr != "" {
		startTime, err = time.Parse(time.RFC3339, startTimeStr)
		if err != nil {
			c.JSON(400, gin.H{"error": "invalid startTime format"})
			return
		}
	}

	if endTimeStr != "" {
		endTime, err = time.Parse(time.RFC3339, endTimeStr)
		if err != nil {
			c.JSON(400, gin.H{"error": "invalid endTime format"})
			return
		}
	}

	logs, err := s.repo.ListLogs(taskID, startTime, endTime)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, logs)
}

func (s *TaskLogService) GetLatestLog(c *gin.Context) {
	taskID := c.Query("taskId")
	if taskID == "" {
		c.JSON(400, gin.H{"error": "taskId is required"})
		return
	}

	log, err := s.repo.GetLatestLog(taskID)
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, log)
}
